import { userGetUserRolePermApi } from './apis/user'
import router, { asyncRoutes } from './router'
import { useUserStore } from './stores/user'
import { useMenuStore } from './stores/menu'
import {
  getFirstRoutePerms,
  getRoutes,
  getSecondRoutePerms,
} from './utils/format'

const whiteList = ['/login', '/404']

router.beforeEach(async (to, from, next) => {
  const store = useUserStore()
  const menuStore = useMenuStore()

  if (store.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.profile.id) {
        // 1、获取用户信息
        const res = await userGetUserRolePermApi()
        store.setProfile(res)
        console.log('权限', res.permissions)
        // 2、根据用户权限筛选路由
        const firstRoutePerms = getFirstRoutePerms(res.permissions)
        const secondRoutePerms = getSecondRoutePerms(res.permissions)
        const filterRoutes = getRoutes(
          firstRoutePerms,
          secondRoutePerms,
          asyncRoutes,
        )
        // 3、动态添加路由
        filterRoutes.forEach((route) => {
          router.addRoute(route)
        })
        // 4、保存路由信息至pinia
        menuStore.setMenuList(filterRoutes)
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach(() => {})
